package com.aop.SpElAop.DistributedLock.RedisLock.LockType;

/**
 * @Package: com.aop.SpElAop.Lock
 * @ClassName: AbstractLock
 * @Author: h2cloud
 * @CreateTime: 2024/7/9 10:07 下午
 * @Description:
 */


import com.aop.SpElAop.DistributedLock.Lock;
import com.aop.SpElAop.DistributedLock.RedisLock.support.LockInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.util.Assert;


@Slf4j
public abstract class AbstractLock implements Lock {

	private final RedissonClient redissonClient;
	private final LockInfo lockInfo;
	private RLock rLock;

	protected AbstractLock(RedissonClient redissonClient, LockInfo lockInfo) {
		this.redissonClient = redissonClient;
		this.lockInfo = lockInfo;
	}

	protected RedissonClient getRedissonClient() {
		return redissonClient;
	}

	@Override
	public LockInfo getLockInfo() {
		return lockInfo;
	}

	/**
	 * 获取 Redisson Lock
	 *
	 * @return RLock
	 */
	protected abstract RLock getRedissonLock();

	@Override
	public boolean lock() {
		try {
			rLock = getRedissonLock();
			if (getLockInfo().isTryLock()) {
				return rLock.tryLock(getLockInfo().getWaitTime(), getLockInfo().getLeaseTime(), getLockInfo().getUnit());
			} else {
				rLock.lock(getLockInfo().getLeaseTime(), getLockInfo().getUnit());
				return true;
			}
		} catch (Exception e) {
			log.error("加锁失败", e);
			return false;
		}
	}

	@Override
	public void unlock() {
		Assert.notNull(rLock, "锁为空，未能执行解锁！");
		rLock.unlock();
	}
}

